from apiV1.models import Card,Comment,Deck,LearnPlan,User
from django.forms.models import model_to_dict
import datetime,json

lostlist = [100,50,33,13,9,6,4,3]
#Card
def ut_addCard(carddict):
    card = Card(
        complexity=carddict.get('complexity'),
        description=carddict.get('description'),
        kind=carddict.get('kind'),
        title=carddict.get('title'),
        popularity=carddict.get('popularity'),
    )
    card.save()
    return card.id

def ut_removeCard(cardid):
    card = Card.objects.filter(id=cardid)
    if card.__len__() == 0:
        return 0
    card.delete()
    return 1

def ut_getCard(data):
    cardid = data.get('cardid')
    card = Card.objects.filter(id=cardid)[0]
    carddict =  model_to_dict(card)
    return carddict

def ut_modifyCard(carddict):
    card = Card.objects.filter(id=carddict.get('id'))
    card.update(
        complexity=carddict.get('complexity'),
        description=carddict.get('description'),
        kind=carddict.get('kind'),
        title=carddict.get('title'),
        popularity=carddict.get('popularity'),
    )
    return carddict


#User
def ut_addUser(userdict):
    user = User(
        name=userdict.get('name'),
        level=userdict.get('level'),
        gold=userdict.get('gold'),
        last_login=userdict.get('last_login')
    )
    user.save()
    return user.id

def ut_removeUser(data):
    userid = data.get('userid')
    User.objects.filter(id=userid).delete()
    return 1

def ut_getUser(data):
    userid = data.get('userid')
    user = User.objects.get(user_id=userid)
    userdict = model_to_dict(user)
    return userdict

def ut_modifyUser(userdict):
    user = User.objects.filter(user_id=userdict.get('id'))
    user.update(
        name=userdict.get('name'),
        level=userdict.get('level'),
        gold=userdict.get('gold'),
        last_login=userdict.get('last_login')
    )
    return 1

#Comment
def ut_addComment(commentdict):
    comment = Comment(
        user_id=commentdict.get('user'),
        card_id=commentdict.get('card'),
        context=commentdict.get('context'),
        kind=commentdict.get('kind'),
        p=0,
        t=0,
    )
    comment.save()
    return comment.id

def ut_removeComment(commentid):
    comment = Comment.objects.filter(id=commentid)
    if comment.__len__() == 0:
        return 0
    comment.delete()
    return 1

def ut_getComment(data):
    commentid = data.get('commentid')
    cardid = data.get('cardid')
    if commentid != None:
        comment = Comment.objects.filter(id=commentid)[0]
        commentdict = model_to_dict(comment)
        return commentdict
    elif cardid != None:
        comments = Comment.objects.filter(card_id=cardid)
        commentsdictlist = []
        for comment in comments:
            commentsdictlist.append(model_to_dict(comment))
        return commentsdictlist
    else:
        return {}

def ut_modifyComment(commentdict):
    comment = Comment.objects.filter(id=commentdict.get('id'))
    if comment.__len__() == 0:
        return 0
    context = commentdict.get('context')
    if context != None:
        comment.update(
            context=commentdict.get('context'),
            kind=commentdict.get('kind'),
            p=0,
            t=0,
        )
    else:
        comment.update(
            kind=commentdict.get('kind'),
            p=commentdict.get('p'),
            t=commentdict.get('t'),
        )
    return 1

#Deck
def ut_addDeck(deckdict):
    deck = Deck(
        titile=deckdict.get('title'),
        description=deckdict.get('description'),
        cards=deckdict.get('cards')
    )
    deck.save()
    return deck.id

def ut_removeDeck(data):
    deckid = data.get('deckid')
    Deck.objects.filter(id=deckid).delete()

def ut_getDeck(data):
    deckid = data.get('deckid')
    if deckid == None:
        decks = Deck.objects.all()
        decksdictlist = []
        for deck in decks:
            cards = deck.cards.split(',')
            carddictlist = []
            for card in cards:
                carddictlist.append(ut_getCard({'cardid': card}))
            deckdict = model_to_dict(deck)
            deckdict['cards'] = carddictlist
            decksdictlist.append(deckdict)
        return decksdictlist
    else:
        deck = Deck.objects.filter(id=deckid)[0]
        cards = deck.cards.split(',')
        carddictlist = []
        for card in cards:
            carddictlist.append(ut_getCard({'cardid':card}))
        deckdict = model_to_dict(deck)
        deckdict['cards'] = carddictlist
        return deckdict

def ut_modifyDeck(deckdict):
    deck = Deck.objects.filter(id=deckdict.get('id'))
    deck.update(
        title=deckdict.get('title'),
        description=deckdict.get('description'),
        cards=deckdict.get('cards'),
    )

#LearnPlan
def ut_addLearnPlan(learnPlandict):
    learnPlan = LearnPlan(
        user_id=learnPlandict.get('user'),
        plan=learnPlandict.get('plan')
    )
    learnPlan.save()
    return learnPlan.id

def ut_removeLearnPlan(data):
    learnPlanid = data.get('learnPlanid')
    LearnPlan.objects.filter(id=learnPlanid).delete()

def ut_getLearnPlan(data):
    learnPlanid = data.get('learnPlanid')
    userid = data.get('userid')
    if learnPlanid != None:
        sourcedate = LearnPlan.objects.filter(id=learnPlanid)[0].plan
    elif userid != None:
        sourcedate = LearnPlan.objects.filter(user_id=userid)[0].plan
    else:
        return {}
    learnPlanUpdata = learnPlan_update(sourcedate)
    learnPlanDict = learnPlanUpdata
    return learnPlanDict

# tool functions
def learnPlan_update(sourcedate):
    sourcedate_splits = sourcedate.split(';')
    le_dicts = []
    for sourcedate_split in sourcedate_splits:
        sourcedate_split_split = sourcedate_split.split('_')
        le_dicts.append({
            'cardid':sourcedate_split_split[0],
            'lastLearn': sourcedate_split_split[1],
            'times': sourcedate_split_split[2],
            'grade': sourcedate_split_split[3],
        })
    now_time = datetime.datetime.now()
    for le_dict in le_dicts:
        last_time = datetime.datetime.strptime(le_dict.get('lastLearn'),'%Y-%m-%d')
        learntimes = int(le_dict.get('times'))
        if learntimes == -1:
            le_dict['grade'] = 0
        elif learntimes > 7:
            le_dict['grade'] = 100
        degrade = (now_time-last_time).days*lostlist[learntimes]
        last_grade = int(le_dict['grade'])
        if degrade > last_grade + 100:
            le_dict['grade'] = -100
        else:
            le_dict['grade'] = last_grade - degrade
        le_dict['card'] = ut_getCard({'cardid':le_dict['cardid']})
    le_dicts.sort(key=lambda le_dict:le_dict.get('grade'))
    return le_dicts


def ut_modifyLearnPlan(learnPlandict):
    learnPlan = LearnPlan.objects.filter(id=learnPlandict.get('id'))
    learnPlan.update(
        plan=learnPlandict.get('plan')
    )

def testdate():
    le_dicts = [
        {
            'lastLearn':'2019-04-29',
            'cardid':32,
            'times':3,
            'grade':100,
        },
        {
            'lastLearn':'2018-04-29',
            'cardid':33,
            'times':6,
            'grade':100,
        },
        {
            'lastLearn':'2019-04-20',
            'cardid':34,
            'times':1,
            'grade':100,
        },
        {
            'lastLearn': '2019-04-20',
            'cardid': 23,
            'times': 8,
            'grade': 100,
        }
    ]